using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;

using System.Text.Json;
using System.Text.Json.Serialization;

using Blogs.LazyFox.Models;
using Blogs.LazyFox.Data;


namespace Blogs.LazyFox.Controllers
{
    [Authorize]
    public class PersonController : Controller
    {
        private readonly BlogsContext _blogsContext;
        private readonly UserManager<PersonModel> _userManager;

        public PersonController(BlogsContext blogsContext, UserManager<PersonModel> userManager)
        {
            _blogsContext = blogsContext;
            _userManager = userManager;
        }

        public async Task<IActionResult> Check(string? id)
        {
            if (id == null)
            {
                id = GetUserId();
            }
            var person = await _blogsContext.Authors.FirstAsync(p => p.Id == id);
            if (person == null)
            {
                return NotFound();
            }
            var j = new PersonModel
            {
                Id = person.Id,
                UserName = person.UserName,
                Email = person.Email,
            };

            return View(j);
        }
        // public async Task<IActionResult> Edit(string? id){
        //     return View();
        // }

        public async Task<IActionResult> Manage()
        {
            var blogs = from b in _blogsContext.Blogs
                        where b.AuthorId == _userManager.GetUserId(HttpContext.User)
                        orderby b.CreateTime descending
                        select b;

            return View(await blogs.ToListAsync());
        }


        private string GetUserId()
        {
            return _userManager.GetUserId(HttpContext.User);
        }
    }
}